package com.wsl.webservice.client;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.*;

/**
 * @Author:wangshuliang
 * @Description:https://www.jianshu.com/p/dd1bf8fa6904
 * @Date:Created in 17:51 2019/5/21
 * @Modified by:
 */
public class LoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private String username = "root";
    private String password = "admin";

    public LoginInterceptor(String username, String password) {
        //设置在发送请求前阶段进行拦截
        super(Phase.PREPARE_SEND);
        this.username = username;
        this.password = password;
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = soapMessage.getHeaders();
        Document document = DOMUtils.createDocument();
        Element auth = document.createElementNS("" +
                "http://server.wsl.com/", "SecurityHeader");
        Element usernameEle = document.createElement("username");
        Element passwordEle = document.createElement("password");
        usernameEle.setTextContent(username);
        passwordEle.setTextContent(password);

        auth.appendChild(usernameEle);
        auth.appendChild(passwordEle);
        headers.add(0,new Header(new QName("SecurityHeader"),auth));

    }
}
